import { defineStore } from 'pinia'
import { useDark } from '@vueuse/core'
import type { GlobalThemeOverrides } from 'naive-ui'
import { naiveThemeOverrides } from '@/settings'
import { lStorage } from '~/src/utils'

const isDark = useDark()

export const useAppStore = defineStore('app', {
  state() {
    return {
      reloadFlag: true,
      collapsed: false,
      aliveKeys: {} as Record<string, number>,
      isDark: isDark.value,
      themeOverrides: {} as GlobalThemeOverrides
    }
  },
  actions: {
    async reloadPage() {
      window.$loadingBar.start()
      this.reloadFlag = false
      await nextTick()
      this.reloadFlag = true

      const timer = setTimeout(() => {
        document.documentElement.scrollTo({ left: 0, top: 0 })
        window.$loadingBar.finish()
        clearTimeout(timer)
      }, 100)
    },
    switchCollapsed() {
      this.collapsed = !this.collapsed
    },
    setCollapsed(collapsed: boolean) {
      this.collapsed = collapsed
    },
    setAliveKeys(key: string, val: number) {
      this.aliveKeys[key] = val
    },
    setDark(isDark: boolean) {
      this.isDark = isDark
    },
    toggleDark() {
      this.isDark = !this.isDark
    },
    setThemeOverrides(themeOverrides = naiveThemeOverrides) {
      this.themeOverrides = themeOverrides
    },
    setThemePrimary(color: string) {
      this.themeOverrides = {
        ...this.themeOverrides,
        common: {
          ...this.themeOverrides.common,
          primaryColor: color + 'FF',
          primaryColorHover: color + 'E3',
          primaryColorPressed: color + 'FF',
          primaryColorSuppl: color + 'E3'
        }
      }
      lStorage.set('primary-color', color)
    }
  }
})
